# -*- encoding: utf-8 -*-
"""
File Name: elastic_info_sender
Description:
Author : 'lirui'
date: 2024/2/8
Contact: marjey_lee@163.com
Change Activity:
2024/2/8:
"""
import json
import urllib3

import ll
from modules.elastic.utils.elastic_client import ElasticClient
from projects.monitoring.alarm_manager.config.config import ELASTIC_LOGIN_INFO

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)


def init_elastic_client() -> ElasticClient:
    """
    init the elastic client.
    Returns:

    """
    client = ElasticClient(
        url=ELASTIC_LOGIN_INFO['url'],
        username=ELASTIC_LOGIN_INFO['username'],
        password=ELASTIC_LOGIN_INFO['password']
    )
    return client


ELASTIC_CLIENT = init_elastic_client()


def send_data_to_elastic(index, doc_id, doc):
    """

    Args:
        index:
        doc_id:
        doc:

    Returns:

    """
    if isinstance(doc, dict) or isinstance(doc, list):
        content = json.dumps(doc)
    else:
        content = doc
    try:
        if not ELASTIC_CLIENT.check_is_connected():
            ELASTIC_CLIENT.refresh_connect()
        ELASTIC_CLIENT.insert(index, doc_id, content)
    except Exception as e:
        ll.get_logger().error(f'Insert data to Elastic error. {e}')
